import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { UserInfo } from '@/types'
import { login as loginApi, getProfile } from '@/api/auth'
import { message } from 'ant-design-vue'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref<UserInfo | null>(null)

  // 登录
  const login = async (username: string, password: string) => {
    try {
      const res = await loginApi({ username, password })
      if (res.data) {
        token.value = res.data.access_token
        localStorage.setItem('token', res.data.access_token)
        message.success('登录成功')
        return true
      }
      return false
    } catch (error: any) {
      message.error(error.message || '登录失败')
      return false
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const res = await getProfile()
      if (res.data) {
        userInfo.value = res.data
      }
    } catch (error) {
      console.error('获取用户信息失败', error)
    }
  }

  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
    message.success('已退出登录')
  }

  return {
    token,
    userInfo,
    login,
    logout,
    fetchUserInfo
  }
})

